import React, { FC, useState, useEffect } from 'react';
import { HistoryTask, UserTask, TaskItem } from '../../type';
import { TaskStatus } from '../../constants';
import { formatTime } from '@/utils/time-utils';
import { Steps } from 'antd-mobile-v2';
import styles from './index.module.less';
import Image from '@/components/Image/TokenImage';
import doneImg from '@/assets/approval/done.png';
import rejectImg from '@/assets/approval/reject.png';
import revertImg from '@/assets/approval/revert.png';
interface IProps {
  historyTask: HistoryTask[];
  srvTime?: number;
  renderMode?: FormRenderModes;
}

const ProcessList: FC<IProps> = (props) => {
  const [historyTaskG, setHistoryTask] = useState<any[]>([]);
  const [currentTask, setCurrentTask] = useState<number>(0);

  useEffect(() => {
    const historyTask = props.historyTask || [];
    const index = historyTask?.map((item) => item.nodeStatus).indexOf(0);
    if (index == -1) {
      setCurrentTask(historyTask.length);
    } else {
      setCurrentTask(index);
    }
    if (!historyTask || !historyTask.length) {
      setHistoryTask([]);
      return;
    }
    let finalHistoryTask = [...historyTask];
    // 过滤后端返回的已结束节点
    if (historyTask[historyTask.length - 1].nodeStatus === undefined) {
      finalHistoryTask = historyTask.slice(0, historyTask.length - 1);
    }
    // 审批中-需要展示已结束节点
    if (index != -1) {
      finalHistoryTask.push({
        userTasks: [
          {
            taskStatusName: '结束',
            noAvator: 1
          }
        ]
      });
    }
    setHistoryTask(finalHistoryTask);
  }, [props.historyTask]);

  const renderReason = (useTask: UserTask) => {
    if (!useTask.handlerComment) {
      return null;
    }
    if (useTask.taskStatus === TaskStatus.Agree) {
      return <div className="longText">同意原因：{useTask.handlerComment}</div>;
    }
    if (useTask.taskStatus === TaskStatus.Reject) {
      return <div className="longText">拒绝原因：{useTask.handlerComment}</div>;
    }
    return <div className="longText">{useTask.handlerComment}</div>;
  };
  const renderProcess = (historyItem: HistoryTask) => {
    if (!historyItem.userTasks) return;
    const userTasks = historyItem.userTasks as TaskItem[];
    const csTasks = historyItem.csUserTasks?.map((el) => {
      return {
        ...el,
        taskStatusName: '已抄送'
      };
    });
    const tasks = userTasks.concat(csTasks || []);
    return tasks.map((taskItem,index) => {
      return (
        <div key={taskItem.taskRecordId || index} className={styles.step}>
          <div className={styles.useInfo}>
            {taskItem.noAvator != 1 && (
              <Image
                className={styles.avator + ' no-print'}
                src={taskItem.handlerIcon}
                defaultImage={require('@/assets/images/defaultAvator.png')}
              />
            )}

            <span className={styles.handlerNameAndStatus}>
              {taskItem.handlerName}
              {taskItem.taskStatusName && taskItem.handlerName ? (
                <span className="dot-symbol"></span>
              ) : null}
              {taskItem.taskStatusName}
            </span>
            {props.srvTime && taskItem.handlerTime ? (
              <div className={styles.time}>
                {formatTime(props.srvTime, taskItem.handlerTime)}
              </div>
            ) : null}
          </div>
          <div className={styles.desc + ' print-no-margin'}>
            {renderReason(taskItem as UserTask)}
          </div>
        </div>
      );
    });
  };
  const renderDot = (currentNode: any) => {
    let status = 'wait';
    if (currentNode) {
      if (currentNode?.nodeStatus == TaskStatus.Reject) {
        status = 'error';
      }
      if (currentNode?.nodeStatus == TaskStatus.Revert) {
        status = 'revert';
      }
      if (
        currentNode?.nodeStatus === TaskStatus.Agree ||
        currentNode?.nodeStatus === TaskStatus.Apply ||
        currentNode?.nodeStatus === TaskStatus.Copy
      ) {
        status = 'finish';
      }
      if (currentNode?.nodeStatus === TaskStatus.Approvaling) {
        status = 'process';
      }
    }
    console.log('status', status);
    if (status === 'finish') {
      return (
        <div style={{ whiteSpace: 'nowrap' }}>
          <img src={doneImg} className={styles.btnIcon} alt="done" />
        </div>
      );
    }
    if (status === 'error') {
      return (
        <div style={{ whiteSpace: 'nowrap' }}>
          <img src={rejectImg} className={styles.btnIcon} alt="reject" />
        </div>
      );
    }
    if (status === 'revert') {
      return (
        <div style={{ whiteSpace: 'nowrap' }}>
          <img src={revertImg} className={styles.btnIcon} alt="revert" />
        </div>
      );
    }
    return null;
  };

  const getStatus = (
    currentNode: any
  ): 'error' | 'finish' | 'wait' | 'process' | 'revert' | undefined => {
    if (currentNode?.nodeStatus == TaskStatus.Reject) {
      return 'error';
    }
    if (currentNode?.nodeStatus == TaskStatus.Revert) {
      return 'revert';
    }
    if (
      currentNode?.nodeStatus === TaskStatus.Agree ||
      currentNode?.nodeStatus === TaskStatus.Apply ||
      currentNode?.nodeStatus === TaskStatus.Copy
    ) {
      return 'finish';
    }
    if (currentNode?.nodeStatus === TaskStatus.Approvaling) {
      return 'process';
    }
    return 'wait';
  };

  return (
    <div className={styles.process}>
      {props.renderMode == 'detail' && (
        <h3 className={styles.processtitle}>审批流程</h3>
      )}
      <Steps
        current={currentTask}
        direction="vertical"
        size="small"
      >
        {historyTaskG.map((historyItem,index) => (
          <Steps.Step
            key={historyItem.taskDefKey || index}
            title={renderProcess(historyItem)}
            status={getStatus(historyItem)}
            icon={renderDot(historyItem)}
          />
        ))}
      </Steps>
    </div>
  );
};

export default ProcessList;
